<template>
  <div class="admin-page">
    <div class="admin-container">
      <div class="page-header">
        <h2>管理后台</h2>
        <p>系统管理与数据统计</p>
      </div>

      <el-tabs v-model="activeTab" class="admin-tabs">
        <!-- 统计概览 -->
        <el-tab-pane label="统计概览" name="statistics">
          <div class="statistics-section">
            <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-icon">👥</div>
                <div class="stat-info">
                  <div class="stat-number">{{ statistics.totalUsers }}</div>
                  <div class="stat-label">总用户数</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">🎰</div>
                <div class="stat-info">
                  <div class="stat-number">{{ statistics.totalLotteries }}</div>
                  <div class="stat-label">总抽奖次数</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">🏆</div>
                <div class="stat-info">
                  <div class="stat-number">{{ statistics.totalWinnings }}</div>
                  <div class="stat-label">总中奖次数</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">📊</div>
                <div class="stat-info">
                  <div class="stat-number">{{ statistics.winRate }}%</div>
                  <div class="stat-label">中奖率</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-icon">🎁</div>
                <div class="stat-info">
                  <div class="stat-number">{{ statistics.totalPrizes }}</div>
                  <div class="stat-label">奖品总数</div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 奖品管理 -->
        <el-tab-pane label="奖品管理" name="prizes">
          <div class="prizes-section">
            <div class="section-header">
              <h3>奖品列表</h3>
              <el-button type="primary" @click="showAddPrizeDialog">
                <el-icon><Plus /></el-icon>
                添加奖品
              </el-button>
            </div>

            <el-table :data="prizes" style="width: 100%">
              <el-table-column prop="name" label="奖品名称" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="probability" label="中奖概率" width="120">
                <template #default="scope">
                  {{ (scope.row.probability * 100).toFixed(2) }}%
                </template>
              </el-table-column>
              <el-table-column prop="quantity" label="数量" width="80" />
              <el-table-column prop="remaining" label="剩余" width="80" />
              <el-table-column label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.active ? 'success' : 'danger'">
                    {{ scope.row.active ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="scope">
                  <el-button size="small" @click="editPrize(scope.row)">编辑</el-button>
                  <el-button 
                    size="small" 
                    :type="scope.row.active ? 'warning' : 'success'"
                    @click="togglePrizeStatus(scope.row)"
                  >
                    {{ scope.row.active ? '禁用' : '启用' }}
                  </el-button>
                  <el-button size="small" type="danger" @click="deletePrize(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 用户管理 -->
        <el-tab-pane label="用户管理" name="users">
          <div class="users-section">
            <div class="section-header">
              <h3>用户列表</h3>
            </div>

            <el-table :data="users" style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="role" label="角色" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.role === 'ADMIN' ? 'danger' : 'primary'">
                    {{ scope.row.role }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="chances" label="剩余次数" width="120" />
              <el-table-column prop="createdAt" label="注册时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template #default="scope">
                  <el-button size="small" @click="addUserChances(scope.row)">
                    增加次数
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 抽奖记录 -->
        <el-tab-pane label="抽奖记录" name="records">
          <div class="records-section">
            <div class="section-header">
              <h3>抽奖记录</h3>
              <div class="filter-controls">
                <el-select
                  v-model="selectedUserId"
                  placeholder="选择用户查看中奖记录"
                  clearable
                  @change="fetchWinningRecords"
                  style="width: 200px; margin-right: 10px;"
                >
                  <el-option
                    v-for="user in users"
                    :key="user.id"
                    :label="user.username"
                    :value="user.id"
                  />
                </el-select>
                <el-switch
                  v-model="showWinningOnly"
                  active-text="仅显示中奖记录"
                  @change="fetchLotteryRecords"
                />
              </div>
            </div>

            <el-table :data="lotteryRecords" style="width: 100%">
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" width="120" />
              <el-table-column prop="prizeName" label="奖品" />
              <el-table-column label="结果" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.isWinner ? 'success' : 'info'">
                    {{ scope.row.isWinner ? '中奖' : '未中奖' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="抽奖时间" width="180">
                <template #default="scope">
                  {{ formatTime(scope.row.createdAt) }}
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="totalRecords"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 添加/编辑奖品对话框 -->
    <el-dialog
      v-model="prizeDialogVisible"
      :title="editingPrize ? '编辑奖品' : '添加奖品'"
      width="500px"
    >
      <el-form :model="prizeForm" :rules="prizeRules" ref="prizeFormRef" label-width="100px">
        <el-form-item label="奖品名称" prop="name">
          <el-input v-model="prizeForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="prizeForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="中奖概率" prop="probability">
          <el-input-number
            v-model="prizeForm.probability"
            :min="0"
            :max="1"
            :step="0.01"
            :precision="4"
          />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="prizeForm.quantity" :min="1" />
        </el-form-item>
        <el-form-item label="剩余数量" prop="remaining">
          <el-input-number v-model="prizeForm.remaining" :min="0" />
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="prizeForm.imageUrl" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="prizeForm.active" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="prizeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePrize">确定</el-button>
      </template>
    </el-dialog>

    <!-- 增加用户次数对话框 -->
    <el-dialog v-model="chancesDialogVisible" title="增加抽奖次数" width="400px">
      <el-form :model="chancesForm" ref="chancesFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="chancesForm.username" disabled />
        </el-form-item>
        <el-form-item label="增加次数" prop="chances">
          <el-input-number v-model="chancesForm.chances" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="chancesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUserChances">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const activeTab = ref('statistics')
const statistics = ref({
  totalUsers: 0,
  totalLotteries: 0,
  totalWinnings: 0,
  winRate: 0,
  totalPrizes: 0
})

const prizes = ref([])
const users = ref([])
const lotteryRecords = ref([])
const showWinningOnly = ref(false)
const selectedUserId = ref(null)

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecords = ref(0)

// 奖品对话框
const prizeDialogVisible = ref(false)
const editingPrize = ref(null)
const prizeForm = reactive({
  name: '',
  description: '',
  probability: 0.01,
  quantity: 1,
  remaining: 1,
  imageUrl: '',
  active: true
})

const prizeRules = {
  name: [{ required: true, message: '请输入奖品名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  probability: [{ required: true, message: '请输入中奖概率', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }]
}

// 用户次数对话框
const chancesDialogVisible = ref(false)
const chancesForm = reactive({
  userId: null,
  username: '',
  chances: 1
})

const prizeFormRef = ref()
const chancesFormRef = ref()

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await axios.get('/api/admin/statistics')
    statistics.value = response.data
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  }
}

// 获取奖品列表
const fetchPrizes = async () => {
  try {
    const response = await axios.get('/api/admin/prizes')
    prizes.value = response.data
    statistics.value.totalPrizes = prizes.value.length
  } catch (error) {
    ElMessage.error('获取奖品列表失败')
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await axios.get('/api/admin/users')
    users.value = response.data
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  }
}

// 获取抽奖记录
const fetchLotteryRecords = async () => {
  try {
    if (showWinningOnly.value) {
      if (!selectedUserId.value) {
        ElMessage.warning('请选择用户以查看中奖记录')
        lotteryRecords.value = []
        totalRecords.value = 0
        return
      }
      const response = await axios.get(`/api/admin/winning-records/${selectedUserId.value}`)
      lotteryRecords.value = response.data
      totalRecords.value = response.data.length
    } else {
      const response = await axios.get(`/api/admin/lottery-records?page=${currentPage.value - 1}&size=${pageSize.value}`)
      lotteryRecords.value = response.data.content
      totalRecords.value = response.data.totalElements
    }
  } catch (error) {
    const message = error?.response?.data?.error || '获取抽奖记录失败'
    ElMessage.error(message)
  }
}

// 获取特定用户的中奖记录
const fetchWinningRecords = async () => {
  if (!selectedUserId.value) {
    // 如果没有选择用户，则获取所有记录
    fetchLotteryRecords()
    return
  }
  
  try {
    const response = await axios.get(`/api/admin/winning-records/${selectedUserId.value}`)
    lotteryRecords.value = response.data
    totalRecords.value = response.data.length
    ElMessage.success(`获取到用户 ${users.value.find(u => u.id === selectedUserId.value)?.username} 的 ${response.data.length} 条中奖记录`)
  } catch (error) {
    ElMessage.error('获取用户中奖记录失败')
    lotteryRecords.value = []
    totalRecords.value = 0
  }
}

// 显示添加奖品对话框
const showAddPrizeDialog = () => {
  editingPrize.value = null
  Object.assign(prizeForm, {
    name: '',
    description: '',
    probability: 0.01,
    quantity: 1,
    remaining: 1,
    imageUrl: '',
    active: true
  })
  prizeDialogVisible.value = true
}

// 编辑奖品
const editPrize = (prize) => {
  editingPrize.value = prize
  Object.assign(prizeForm, {
    name: prize.name,
    description: prize.description,
    probability: prize.probability,
    quantity: prize.quantity,
    remaining: prize.remaining,
    imageUrl: prize.imageUrl,
    active: prize.active
  })
  prizeDialogVisible.value = true
}

// 保存奖品
const savePrize = async () => {
  if (!prizeFormRef.value) return
  
  try {
    await prizeFormRef.value.validate()
    
    if (editingPrize.value) {
      await axios.put(`/api/admin/prizes/${editingPrize.value.id}`, prizeForm)
      ElMessage.success('奖品更新成功')
    } else {
      await axios.post('/api/admin/prizes', prizeForm)
      ElMessage.success('奖品添加成功')
    }
    
    prizeDialogVisible.value = false
    fetchPrizes()
  } catch (error) {
    ElMessage.error('保存奖品失败')
  }
}

// 切换奖品状态
const togglePrizeStatus = async (prize) => {
  try {
    await axios.put(`/api/admin/prizes/${prize.id}`, {
      ...prize,
      active: !prize.active
    })
    ElMessage.success('状态更新成功')
    fetchPrizes()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 删除奖品
const deletePrize = async (prize) => {
  try {
    await ElMessageBox.confirm('确定要删除这个奖品吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await axios.delete(`/api/admin/prizes/${prize.id}`)
    ElMessage.success('奖品删除成功')
    fetchPrizes()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除奖品失败')
    }
  }
}

// 增加用户次数
const addUserChances = (user) => {
  chancesForm.userId = user.id
  chancesForm.username = user.username
  chancesForm.chances = 1
  chancesDialogVisible.value = true
}

// 保存用户次数
const saveUserChances = async () => {
  try {
    await axios.post(`/api/admin/users/${chancesForm.userId}/add-chances`, {
      chances: chancesForm.chances
    })
    ElMessage.success('次数添加成功')
    chancesDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error('添加次数失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchLotteryRecords()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchLotteryRecords()
}

// 格式化时间
const formatTime = (timeString) => {
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchStatistics()
  fetchPrizes()
  fetchUsers()
  fetchLotteryRecords()
})
</script>

<style scoped>
.admin-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.admin-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  text-align: center;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-size: 2rem;
}

.page-header p {
  margin: 0;
  opacity: 0.9;
}

.admin-tabs {
  padding: 20px;
}

.statistics-section {
  padding: 20px 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 25px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  gap: 15px;
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  font-size: 2.5rem;
  opacity: 0.8;
}

.stat-number {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.9;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #2c3e50;
}

.filter-controls {
  display: flex;
  gap: 15px;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
}
</style>